import mysql.connector
import sys
import os

# 添加服务器目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), 'server'))

# 从配置文件导入数据库配置
from app.utils.config import settings

# 数据库配置
db_config = {
    'host': settings.DB_HOST,
    'user': settings.DB_USER,
    'password': settings.DB_PASSWORD,
    'database': settings.DB_NAME,
    'port': settings.DB_PORT
}

try:
    # 连接到数据库
    conn = mysql.connector.connect(**db_config)
    cursor = conn.cursor()
    
    # 获取表结构
    cursor.execute("DESCRIBE tb_bbe_patient_info")
    columns = cursor.fetchall()
    
    print("Table structure for tb_bbe_patient_info:")
    print("{:<30} {:<20} {:<10} {:<10} {:<20} {:<20}".format(
        "Field", "Type", "Null", "Key", "Default", "Extra"))
    print("-" * 120)
    
    # 显示前10列
    print("First 10 columns:")
    for i in range(min(10, len(columns))):
        column = columns[i]
        print("{:<30} {:<20} {:<10} {:<10} {:<20} {:<20}".format(
            str(column[0]), str(column[1]), str(column[2]), 
            str(column[3]), str(column[4]), str(column[5])))
    
    print("\n... (skipping middle columns) ...\n")
    
    # 显示最后10列
    print("Last 10 columns:")
    start_index = max(10, len(columns) - 10)
    for i in range(start_index, len(columns)):
        column = columns[i]
        print("{:<30} {:<20} {:<10} {:<10} {:<20} {:<20}".format(
            str(column[0]), str(column[1]), str(column[2]), 
            str(column[3]), str(column[4]), str(column[5])))
        
    # 检查是否有我们尝试插入的字段
    field_names = [column[0] for column in columns]
    print(f"\nTotal number of columns: {len(field_names)}")
    
    # 检查一些关键字段是否存在
    key_fields = ['id', 'AGE', '检查时间', '检查医院']
    print("\nChecking for key fields:")
    for field in key_fields:
        if field in field_names:
            print(f"  ✓ '{field}' exists")
        else:
            print(f"  ✗ '{field}' does not exist")
        
    cursor.close()
    conn.close()
    
except Exception as e:
    print(f"Error: {e}")